package cn.innosmart.aq.view.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.TextView;

import com.tutk.p2p.ConnectionEntity;
import com.tutk.p2p.ConnectionManager;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import cn.innosmart.aq.R;
import cn.innosmart.aq.adapter.RuleListAdapter;
import cn.innosmart.aq.bean.ActionBean;
import cn.innosmart.aq.bean.AquariumBean;
import cn.innosmart.aq.bean.CommandBean;
import cn.innosmart.aq.bean.DeviceBean;
import cn.innosmart.aq.bean.RuleBean;
import cn.innosmart.aq.bean.SceneBean;
import cn.innosmart.aq.bean.TriggerBean;
import cn.innosmart.aq.bean.ValueConditionBean;
import cn.innosmart.aq.customize.CustomsizeDialog;
import cn.innosmart.aq.manager.RuleManager;
import cn.innosmart.aq.util.DeviceConstant;
import cn.innosmart.aq.util.SystemConstant;
import cn.innosmart.aq.view.activity.RuleActivity;

/**
 * Created by David on 2015/11/24.
 */
public class BoxDetailRuleFragment extends BaseFragment {
    private final int LOADINGOVER = 0;
    private final int DATACHANGE = 7;
    int[] priorityStrIds = new int[]{R.string.priority_ignore_simple, R.string.priority_normal_simple, R.string.priority_important_simple, R.string.priority_high_important_simple};
    private View view;
    private ListView listView;
    private RuleListAdapter ruleListAdapter;
    private ConnectionEntity connectionEntity;
    private BoxDetailAutoFragment parent;
    private AquariumBean aquariumBean;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case LOADINGOVER:
                    hideLoadingDialog();
                    break;
                case DATACHANGE:
                    onResume();
                    break;
            }
        }
    };
    private View.OnClickListener onModifyClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.tv_modify:
                    //修改规则
                    modifyRule(v);
                    break;
                case R.id.fcb_control:
                    //开启 关闭规则
                    switchRule(v);
                    break;
                case R.id.tv_delete:
                    //删除规则
                    RuleBean ruleBean = (RuleBean) v.getTag();
                    showSureDeleteDialog(ruleBean.getTitle(), ruleBean);
                    break;
                case R.id.tv_info:
                    //显示规则信息
                    showAutoInfo(v);
                    break;
            }
        }
    };

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_auto_example, container, false);
        connectionEntity = ConnectionManager.getInstance().getCurrentConnectionEntity();
        parent = (BoxDetailAutoFragment) getParentFragment();
        aquariumBean = parent.getAquariumBean();
        listView = (ListView) view.findViewById(R.id.lv_auto);
        TextView emptyView = (TextView) view.findViewById(R.id.empty_view);
        emptyView.setText(R.string.no_rule_data);
        listView.setEmptyView(emptyView);
        ruleListAdapter = new RuleListAdapter(getActivity(), aquariumBean);
        ruleListAdapter.setOnModifyClickListener(onModifyClickListener);
        listView.setAdapter(ruleListAdapter);
        return view;
    }

    /**
     * 切换规则 开启 关闭
     *
     * @param v
     */
    private void switchRule(View v) {
        showLoadingDialog(getActivity());
        final RuleBean ruleBean = (RuleBean) v.getTag();
        JSONObject jsonParams = new JSONObject();
        try {
            jsonParams.put("id", ruleBean.getId());
        } catch (JSONException e) {
            e.printStackTrace();
        }
        if (ruleBean.getEnabled() == 1) {
            RuleManager.getInstance().Disable(connectionEntity, jsonParams, new RuleManager.DisableCallBack() {
                @Override
                public void onDisableResponseCallBack(int ret, String ruleid) {
                    if (ret == 0) {
                        ruleBean.setEnabled(0);
                        showToast(getActivity().getString(R.string.rule_disable));
                        mHandler.sendEmptyMessage(DATACHANGE);
                        hideLoadingDialog();
                    } else {
                        ruleBean.setEnabled(1);
                        showToast(getActivity().getString(R.string.rule_disable_failed));
                        mHandler.sendEmptyMessage(DATACHANGE);
                        hideLoadingDialog();
                    }
                }
            });
        } else {
            RuleManager.getInstance().Enable(connectionEntity, jsonParams, new RuleManager.EnableCallBack() {
                @Override
                public void onEnableResponseCallBack(int ret, String ruleid) {
                    if (ret == 0) {
                        ruleBean.setEnabled(1);
                        showToast(getActivity().getString(R.string.rule_enable));
                        mHandler.sendEmptyMessage(DATACHANGE);
                        hideLoadingDialog();
                    } else {
                        ruleBean.setEnabled(0);
                        showToast(getActivity().getString(R.string.rule_enable_failed));
                        mHandler.sendEmptyMessage(DATACHANGE);
                        hideLoadingDialog();
                    }
                }
            });
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        refresh();
        startModify(parent.isModify);
    }

    /**
     * 刷新数据
     */
    @Override
    protected void refresh() {
        if (ruleListAdapter != null) {
            aquariumBean = parent.getAquariumBean();
            ruleListAdapter.setAquariumBean(aquariumBean);
            ruleListAdapter.refresh();
        }
    }

    /**
     * 进入修改模式
     *
     * @param startModify
     */
    @Override
    protected void startModify(boolean startModify) {
        if (ruleListAdapter != null)
            ruleListAdapter.startModify(startModify);
    }

    /**
     * 确认删除对话框
     *
     * @param name
     * @param object
     */
    private void showSureDeleteDialog(String name, final Object object) {
        final CustomsizeDialog customsizeDialog = new CustomsizeDialog(getActivity());
        customsizeDialog.setTitle(getActivity().getString(R.string.dialog_title_alert));
        customsizeDialog.setContent(String.format(getString(R.string.dialog_content_delete_sure), name));
        customsizeDialog.setNegativeButton(getActivity().getString(R.string.cancel), new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                customsizeDialog.dismiss();
            }
        });
        customsizeDialog.setPositiveButton(getActivity().getString(R.string.sure), new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showLoadingDialog(getActivity());
                final RuleBean ruleBeanDelete = (RuleBean) object;
                RuleManager.getInstance().Remove(connectionEntity, ruleBeanDelete.toDeleteParams(), new RuleManager.RemoveCallBack() {
                    @Override
                    public void onRemoveResponseCallBack(int ret, String ruleid) {
                        if (ret == 0) {
                            SystemConstant.ruleList.remove(ruleBeanDelete);
                            parent.getAquariumBean().getRuleList().remove(ruleBeanDelete);
                            mHandler.sendEmptyMessage(DATACHANGE);
                            hideLoadingDialog();
                        }
                    }
                });
                customsizeDialog.dismiss();
            }
        });
        customsizeDialog.show();
    }

    /**
     * 修改规则
     *
     * @param v
     */
    private void modifyRule(View v) {
        RuleBean ruleBean = (RuleBean) v.getTag();
        Intent intent = new Intent(getActivity(), RuleActivity.class);
        intent.putExtra("aquarium", aquariumBean.getId());
        intent.putExtra("rule", ruleBean.getId());
        startActivity(intent);
        getActivity().overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
    }

    /**
     * 显示自动控制的简要信息
     * @param v
     */
    private void showAutoInfo(View v) {
        final CustomsizeDialog autoInfoDialog = new CustomsizeDialog(getActivity());
        autoInfoDialog.setTitle(getActivity().getString(R.string.auto_info_title));
        RuleBean ruleBean = (RuleBean) v.getTag();
        spellRuleInfo(ruleBean, autoInfoDialog);
        autoInfoDialog.setPositiveButton(R.string.sure, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                autoInfoDialog.dismiss();
            }
        });
        autoInfoDialog.show();
    }

    /**
     * 拼接 规则信息
     * @param ruleBean
     * @param autoInfoDialog
     */
    private void spellRuleInfo(RuleBean ruleBean, CustomsizeDialog autoInfoDialog) {
        StringBuilder autoInfo = new StringBuilder();
        HashMap<String, TriggerBean> triggers = ruleBean.getTriggers();
        Iterator iterator = triggers.entrySet().iterator();
        int i = 1;
        while (iterator.hasNext()) {
            Map.Entry entry = (Map.Entry) iterator.next();
            String address = (String) entry.getKey();
            DeviceBean deviceBean = SystemConstant.deviceBeanHashMap.get(address);
            String deviceName = deviceBean.getName();
            TriggerBean val = (TriggerBean) entry.getValue();
            ValueConditionBean conditionBean = val.getValueConditionBeans().get(0);
            if (i == 1) {
                autoInfo.append(i + "、" + deviceName);
                if (deviceBean.getFunctype() == DeviceConstant.FUNCTYPE_WATERLEVER) {
                    if (conditionBean.getThreshold() == 1) {
                        autoInfo.append(getActivity().getString(R.string.lower));
                    }
                    if (conditionBean.getThreshold() == 2) {
                        autoInfo.append(getActivity().getString(R.string.higher));
                    }
                } else {
                    autoInfo.append(" " + conditionBean.getOp() + " " + DeviceConstant.caculateValue(deviceBean.getSensorunit(), conditionBean.getThreshold()));
                }
            } else {
                autoInfo.append("\r\n");
                autoInfo.append(i + "、" + deviceName);
                if (deviceBean.getFunctype() == DeviceConstant.FUNCTYPE_WATERLEVER) {
                    if (conditionBean.getThreshold() == 1) {
                        autoInfo.append(getActivity().getString(R.string.lower));
                    }
                    if (conditionBean.getThreshold() == 2) {
                        autoInfo.append(getActivity().getString(R.string.higher));
                    }
                } else {
                    autoInfo.append(" " + conditionBean.getOp() + " " + DeviceConstant.caculateValue(deviceBean.getSensorunit(), conditionBean.getThreshold()));
                }
            }
            i++;
        }
        autoInfoDialog.setConditionContent(getActivity().getString(R.string.condition), autoInfo.toString());
        autoInfo = new StringBuilder();
        ArrayList<CommandBean> arrayList = ruleBean.getCommands();
        for (int j = 1; j < arrayList.size() + 1; j++) {
            CommandBean commandBean = arrayList.get(j - 1);
            String command = "";
            if ("sleep".equals(commandBean.getType())) {
                command = getActivity().getString(R.string.sleep) + commandBean.getValue() + getActivity().getString(R.string.sleep_unit);
            } else if ("scene".equals(commandBean.getType())) {
                String sceneId = commandBean.getScene_id();
                SceneBean sceneBean = SceneBean.queryScene(sceneId);
                command = getActivity().getString(R.string.scene) + sceneBean.getTitle();
            } else if ("commands".equals(commandBean.getType())) {
                ArrayList<ActionBean> actionBeans = commandBean.getCommand();
                ActionBean actionBean = actionBeans.get(0);
                DeviceBean deviceBean = SystemConstant.deviceBeanHashMap.get(actionBean.getAddress());
                String name = deviceBean.getName();
                if (actionBean.getValue() == 255) {
                    command = name + getActivity().getString(R.string.open);
                } else {
                    command = name + getActivity().getString(R.string.close);
                }

            }
            if (j == 1) {
                autoInfo.append(j + "、" + command);
            } else {
                autoInfo.append("\r\n");
                autoInfo.append(j + "、" + command);
            }
        }
        autoInfoDialog.setCommandContent(getActivity().getString(R.string.command), autoInfo.toString());
        autoInfo = new StringBuilder();
        if (ruleBean.getRepeat_type() != 0) {
            autoInfo.append(ruleBean.getStart() + "~" + ruleBean.getEnd());
        } else {
            autoInfo.append(getActivity().getString(R.string.always));
        }
        if (ruleBean.getRepeat_type() != 0) {
            autoInfo.append("\r\n");
            HashMap<Integer, JSONArray> timeLine = ruleBean.getTimeLine();
            for (int j = 0; j < 7; j++) {
                if (timeLine.get(j) != null) {
                    switch (j) {
                        case 0:
                            autoInfo.append(getActivity().getString(R.string.sunday));
                            autoInfo.append(",");
                            break;
                        case 1:
                            autoInfo.append(getActivity().getString(R.string.monday));
                            autoInfo.append(",");
                            break;
                        case 2:
                            autoInfo.append(getActivity().getString(R.string.tuesday));
                            autoInfo.append(",");
                            break;
                        case 3:
                            autoInfo.append(getActivity().getString(R.string.wensday));
                            autoInfo.append(",");
                            break;
                        case 4:
                            autoInfo.append(getActivity().getString(R.string.thursday));
                            autoInfo.append(",");
                            break;
                        case 5:
                            autoInfo.append(getActivity().getString(R.string.friday));
                            autoInfo.append(",");
                            break;
                        case 6:
                            autoInfo.append(getActivity().getString(R.string.saturday));
                            autoInfo.append(",");
                            break;
                    }
                }
            }
            autoInfo.replace(autoInfo.length() - 1, autoInfo.length(), "");
        }
        autoInfoDialog.setValidContent(getActivity().getString(R.string.worktime), autoInfo.toString());
        autoInfo = null;
        if (ruleBean.getEnabled() == 1) {
            autoInfoDialog.setStatusContent(getActivity().getString(R.string.status), getActivity().getString(R.string.start));
        } else {
            autoInfoDialog.setStatusContent(getActivity().getString(R.string.status), getActivity().getString(R.string.close));
        }
        if (TextUtils.isEmpty(ruleBean.getPns())) {
            autoInfoDialog.setPushContent(getActivity().getString(R.string.push_status), getActivity().getString(R.string.close));
        } else {
            autoInfoDialog.setPushContent(getActivity().getString(R.string.push_status), getActivity().getString(R.string.open));
        }
        if (ruleBean.pns_priority != 0)
            autoInfoDialog.setImportanceContent(getActivity().getString(R.string.alarm_priority_title), getActivity().getString(priorityStrIds[ruleBean.pns_priority]));

    }
}
